package com.example.elmmerchants.Create_Shop;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.elmmerchants.R;
import com.example.elmmerchants.SQL.Connection_SQL;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Legal_Information_Page extends AppCompatActivity {

    String user_email, shop_status, qualification_status, legal_status, id_card_front_string = "", id_card_reverse_string = "";
    TextView shop_information_status, qualification_information_status, legal_information_status;
    LinearLayout go_to_upload_id_card_under, go_to_upload_id_card_front;

    ImageView id_card_front, id_card_reverse;
    boolean is_loading_data = false, is_id_card_front = false, is_id_card_under = false, is_upload_data = false;
    Button next_step;
    byte[] front = new byte[0];
    byte[] under = new byte[0];
    AlertDialog dialog;

    private class Loading_Data_Thread extends Thread {
        @Override
        public void run() {
            is_loading_data = false;
            is_id_card_front = false;
            is_id_card_under = false;
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL connectionSql = new Connection_SQL();
                    Connection connection = connectionSql.connection();
                    String sql = "SELECT * FROM merchant WHERE email = ?;";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, user_email);
                    ResultSet set = preparedStatement.executeQuery();
                    while (set.next()) {
                        if (set.getBlob("id_card_front") != null) {
                            front = set.getBytes("id_card_front");
                            is_id_card_front = true;
                        }
                        if (set.getBlob("id_card_under") != null) {
                            under = set.getBytes("id_card_under");
                            is_id_card_under = true;
                        }
                    }
                    is_loading_data = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_loading_data) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dialog.dismiss();
                    if (is_id_card_front) {
                        Bitmap decodedImage = BitmapFactory.decodeByteArray(front, 0, front.length);
                        id_card_front.setImageBitmap(decodedImage);
                    }
                    else {
                        go_to_upload_id_card_front.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                Intent intent = new Intent(Legal_Information_Page.this, ID_Card_Front_Page.class);
                                intent.putExtra("user_email", user_email);
                                startActivityForResult(intent, 1);
                            }
                        });
                    }

                    if (is_id_card_under) {
                        Bitmap decodedImage2 = BitmapFactory.decodeByteArray(under, 0, under.length);
                        id_card_reverse.setImageBitmap(decodedImage2);
                    }
                    else {
                        go_to_upload_id_card_under.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                Intent intent = new Intent(Legal_Information_Page.this, ID_Card_Under_Page.class);
                                intent.putExtra("user_email", user_email);
                                startActivityForResult(intent, 1);
                            }
                        });
                    }
                }
            });
        }
    }

    private class Upload_Data_Thread extends Thread {
        @Override
        public void run() {
            is_upload_data = false;

            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL connectionSql = new Connection_SQL();
                    Connection connection = connectionSql.connection();
                    String sql = "update `merchant` set legal_information = ? where email = ?";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setInt(1, 1);
                    preparedStatement.setString(2, user_email);
                    preparedStatement.executeUpdate();
                    is_upload_data = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }

                while (!is_upload_data) {
                    try {
                        Thread.sleep(1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dialog.dismiss();
                        Intent intent = new Intent(Legal_Information_Page.this, Set_Shop_Data.class);
                        setResult(1, intent);
                        finish();
                    }
                });
            });
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_legal_information_page);

        user_email = getIntent().getStringExtra("user_email");
        shop_status = getIntent().getStringExtra("shop_information_status");
        qualification_status = getIntent().getStringExtra("qualification_information_status");
        legal_status = getIntent().getStringExtra("legal_information_status");

        shop_information_status = findViewById(R.id.shop_information_status);
        qualification_information_status = findViewById(R.id.qualification_information_status);
        legal_information_status = findViewById(R.id.legal_information_status);
        go_to_upload_id_card_front = findViewById(R.id.go_to_upload_id_card_front);
        go_to_upload_id_card_under = findViewById(R.id.go_to_upload_id_card_under);
        id_card_front = findViewById(R.id.id_card_front);
        id_card_reverse = findViewById(R.id.id_card_reverse);
        next_step = findViewById(R.id.next_step);

        if (shop_status.equals("已录入")) {
            shop_information_status.setText("已完成");
        }

        if (qualification_status.equals("已录入")) {
            qualification_information_status.setText("已完成");
        }

        if (legal_status.equals("已录入")) {
            legal_information_status.setText("已完成");
        }

        get_id_card_data();
    }

    void get_id_card_data() {
        set_dialog();

        Loading_Data_Thread loadingDataThread = new Loading_Data_Thread();
        loadingDataThread.start();

        next_step.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (is_id_card_front && is_id_card_under) {
                    set_dialog();
                    Upload_Data_Thread uploadDataThread = new Upload_Data_Thread();
                    uploadDataThread.start();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case 1: {
                get_id_card_data();
            }
        }
    }

    public void set_dialog() {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
        LayoutInflater inflater1 = LayoutInflater.from(this);
        builder.setView(inflater1.inflate(R.layout.loading, null));
        builder.setCancelable(false);

        dialog = builder.create();
        dialog.show();
    }
}